The iterator notation is easiest.
In [4]:
f = open('kaiju_movies.dat')
for movie in f:
print movie,
f.close()
(The comma at the end suppresses extra newline). Can also use the object-oriented interface.
In [5]:
f = file('kaiju_movies.dat')
for movie in f:
print movie,
f.close()
In [6]:
f = open('kaiju_movies.dat')
movies = f.readlines()
print movies
f.close()
In [7]:
dumb_monsters = ('Hedorah', 'Megalon', 'Gigan', 'Minilla')
f = open('monsters.txt', 'w')
for monster in dumb_monsters:
f.write(monster + '\n')
f.close()
This approach does not add newlines, so add them yourself if needed.
In [2]:
dumb_monsters = ('Hedorah', 'Megalon', 'Gigan', 'Minilla')
f = open('monsters2.txt', 'w')
f.writelines(dumb_monsters)
f.close()
Open and close similar to text files, but use read() and write().
In [8]:
f = open('nikki.jpg', 'rb')
my_dog = f.read()
f.close()
# Do arbitrary stuff with data.
f = open('new_nikki.jpg', 'wb')
f.write(my_dog)
f.close()
Format-specific binary I/O is available through standard modules, like Image.
In [9]:
from IPython.display import Image
puppeh = Image(filename = 'nikki.jpg')
puppeh
Out[9]:
The pickle is an internal Python format for writing arbitrary data to a file in a way that allows it to be read in again, intact.
In [10]:
movies = [{'title': 'Godzilla', 'year': 1954}, {'title': 'Godzilla 2000: Millennium', 'year': 1999}]
import pickle
f = open('pickled_kaiju.pkl', 'wb')
pickle.dump(movies, f)
f.close()
In [11]:
f = open('pickled_kaiju.pkl', 'rb')
pickled_movies = pickle.load(f)
f.close()
print pickled_movies
There is much more to file I/O in Python - binary data, reading and writing through network connections, other object serialization methods. Dive into that when you are comfortable with basic text input and output.